package com.example.esaclient;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Request.Callback;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.model.GraphObject;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.conf.ConfigurationBuilder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class SearchActivity extends Activity {

	EditText txtSearchKey ;	
	ProgressDialog dialog;
	public String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/ESAClient/cache";
	ArrayList<HashMap<String, Object>> data;
	 Spinner spinner ;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		 txtSearchKey =(EditText)findViewById(R.id.txtSearch);	
		 
		  spinner = (Spinner) findViewById(R.id.Social_spinner);
		
		
	}

	
	public void search(View v) {
	
		// clear chache folder
		File folder = new File(path);

		if (folder.isDirectory()) {
			String[] children = folder.list();
			for (int i = 0; i < children.length; i++) {
				new File(folder, children[i]).delete();
			}
		}
		GlobalSettings gs = new GlobalSettings(SearchActivity.this);
		AlertDialogManager alert =  new AlertDialogManager();
		if (spinner.getSelectedItem().toString().equals("Twitter")){
			
			if(gs.getPrefBool(gs.PREF_KEY_TWITTER_LOGIN)==false)
			{

				alert.showAlertDialog(SearchActivity.this,
						"Not connected to Twitter",
						"You must have an active Twitter account associated to ESA to perform a search.", false);
				return;
			}
			
			dialog = ProgressDialog.show(this, "Searching on Twitter",
					"Please wait...", true);

			new TwitterSearch(this).execute(txtSearchKey.getText().toString());
		}
		else if (spinner.getSelectedItem().toString().equals("Facebook")) {

			if(gs.getPrefBool(gs.PREF_KEY_FACEBOOK_LOGIN)==false)
			{

				alert.showAlertDialog(SearchActivity.this,
						"Not connected to Facebook",
						"You must have an active Facebook account associated to ESA to perform a search.", false);
				
				
			}
			
			dialog = ProgressDialog.show(this, "Searching on Facebook",
					"Please wait...", true);

			Session.openActiveSession(this, true, new Session.StatusCallback() {

				// callback when session changes state
				@Override
				public void call(Session session, SessionState state,
						Exception exception) {

					if (session.isOpened()) {
						String grapPath = "search";
						Bundle params = new Bundle();
						params.putString("q", txtSearchKey.getText().toString());
						params.putString("type", "post");
						params.putString("fileds", "message,from");

						Request request = new Request(session, grapPath,
								params, HttpMethod.GET, new Callback() {

									@Override
									public void onCompleted(Response response) {
										if (response != null) {
											GraphObject graphObject = response
													.getGraphObject();
											new FacebookSearch(
													SearchActivity.this)
													.execute(graphObject);
										}

									}
								});

						RequestAsyncTask task = new RequestAsyncTask(request);
						task.execute();
					}
				}
			});
		}
	}
	


	

	public void parseTWResult( List<twitter4j.Status> l){
		ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
		
		
		for (twitter4j.Status qstatus : l) {
			HashMap<String, Object> feed=new HashMap<String, Object>();
			feed.put("message", qstatus.getText());
			feed.put("time", qstatus.getCreatedAt().toString());
			feed.put("socialNetwork","Via Twitter");			
			feed.put("taggerPicture", EsaTag.loadImageFromWebOperations(qstatus.getUser().getBiggerProfileImageURL(), path));			
			feed.put("tagger",qstatus.getUser().getScreenName());
			
			data.add(feed);
			
		}
		fillList(data);
	}
	
	public void fillList(ArrayList<HashMap<String,Object>> result){
		dialog.dismiss();

		if(data==null)
			data=new ArrayList<HashMap<String,Object>>();
		
		
		data.clear();
		if(result!=null)
		data.addAll(result);
		
		if (data.size() > 0) {

			runOnUiThread(new Runnable() {
				public void run() {
					String[] from = { "message", "time", "socialNetwork",
							"taggerPicture", "tagger" }; // from values of
															// hashMap
					int[] to = { R.id.lstTAGMessage, R.id.lstTAGtime,
							R.id.lstTAGFrom, R.id.lstTAGImage, R.id.lstTagger };

					SimpleAdapter adapter = new SimpleAdapter(
							SearchActivity.this, data,// data source
							R.layout.feed_tag_element, // layout of a single
														// feed element
							from, to);
					((ListView) SearchActivity.this
							.findViewById(R.id.search_list))
							.setAdapter(adapter);

					adapter.notifyDataSetChanged();

				}
			});

			}
		
	}
	

	 private class FacebookSearch extends AsyncTask<GraphObject, Void, Void> {
		 
		 SearchActivity caller;
			 String queryString;
			 
			public FacebookSearch(SearchActivity callerActivity){
				caller=callerActivity;
				
			}
		 
		    @Override
		    protected Void doInBackground(GraphObject... param) {
		    	
		    	GraphObject graphObject =param[0];
         	   if (graphObject != null) {
       		   JSONObject  jsonObject = graphObject.getInnerJSONObject();
       		   	ArrayList<HashMap<String, Object>> FeedData=new ArrayList<HashMap<String,Object>>();
     		   	
                 String s,date,time="";
                     JSONArray array;
    				try {
    					array = jsonObject.getJSONArray("data");
    			
    					
                     for (int i = 0; i < array.length(); i++) {
                   	   try {
                         JSONObject object = (JSONObject) array.get(i);
                         HashMap<String, Object> feed=new HashMap<String, Object>();
                         s=(String) object.get("updated_time");	                              
                         String[] tmpDate=s.split("T")[0].split("\\-");
                         date=tmpDate[2]+"/"+tmpDate[1]+"/"+tmpDate[0];
                         time=s.split("T")[1].split("\\+")[0];
             			feed.put("message", (String) object.get("message"));
             			feed.put("time",date + " "+time);
             			feed.put("socialNetwork","Via Facebook");			
             			feed.put("taggerPicture", EsaTag.loadImageFromWebOperations("http://graph.facebook.com/"+object.getJSONObject("from").get("id")+"/picture",path));			
             			feed.put("tagger",object.getJSONObject("from").get("name"));
             			
             			FeedData.add(feed);
             				                            
                     
                   	   } catch (JSONException e) {

    	                      e.printStackTrace();
    	                     }
                      }
                     
    				} catch (JSONException e1) {
    					
    					e1.printStackTrace();
    				}
    				fillList(FeedData);
    		   	 
         	   }
		   	 
		   	
			return null;
		    	
		    }
		    
	 }
	
	 private class TwitterSearch extends AsyncTask<String, Void, List<twitter4j.Status>> {
		 
		 SearchActivity caller;
			
			public TwitterSearch(SearchActivity callerActivity){
				caller=callerActivity;
			}
		 
		    @Override
		    protected List<twitter4j.Status> doInBackground(String... param) {
		    	
		    	String accessToken = "",accessTokenSecret="";
		    	
		    String s =new GlobalSettings(caller).getPrefString(GlobalSettings.PREF_TWITTER_TOKEN);
		    String [] t;
		    if(!s.equals("")){
		    t=s.split(";");
		    accessToken=t[0];
		    	accessTokenSecret=t[1];
		    }
		    	
		    	 ConfigurationBuilder cb = new ConfigurationBuilder();
				    cb.setDebugEnabled(true)
				          .setOAuthConsumerKey("RUMoRPLvEHqN9dPoFIiwQ")
				          .setOAuthConsumerSecret("krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE")
				          .setOAuthAccessToken(accessToken)
				          .setOAuthAccessTokenSecret(accessTokenSecret);
				    TwitterFactory tf = new TwitterFactory(cb.build());
				    Twitter twitter = tf.getInstance();
				    
				    List<twitter4j.Status> result ;
				String queryString =param[0];
				try {

				
					
					Query query = new Query(queryString);
					QueryResult qresult;
					qresult = twitter.search(query);
					
				//	for (twitter4j.Status qstatus : qresult.getTweets()) {}
					
					result=  qresult.getTweets();
					caller.parseTWResult(result);
					 return result;
					
				} catch (TwitterException e) {

					e.printStackTrace();
				}
		      return null;
		    }

		    @Override
		    protected void onPostExecute( List<twitter4j.Status> result) {
		    	
		    }
		  }

}
